package com.ruyuan.eshop.buyer.config;

import com.ruyuan.eshop.framework.context.LoginUserContext;
import com.ruyuan.eshop.framework.core.JsonResult;
import com.ruyuan.eshop.framework.exception.CommonErrorCodeEnum;
import com.ruyuan.eshop.framework.utils.JWTUtil;
import com.ruyuan.eshop.framework.utils.ServletUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 登录信息验证拦截器
 * </p>
 *
 * @author pwd
 * @version 1.0
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if(token == null) {
            token = request.getParameter("token");
        }

        // token不为空
        if(StringUtils.isNotBlank(token)) {
            Claims claims = JWTUtil.checkJWT(token);
            if(claims == null) {
                //未登录
                ServletUtil.sendJsonMessage(response, JsonResult.buildError(CommonErrorCodeEnum.SERVER_USER_NOT_LOGIN_ERROR));
                return false;
            }

            Long id = null;
            if(claims.get("id") != null) {
                id = Long.valueOf(claims.get("id").toString());
            }
            String username = (String)claims.get("username");
            BuyerLoginUser loginUser = new BuyerLoginUser(id, username, null);

            LoginUserContext.setLoginUser(loginUser);
            LoginUserContext.setToken(token);

            return true;

        }

        ServletUtil.sendJsonMessage(response, JsonResult.buildError(CommonErrorCodeEnum.SERVER_USER_NOT_LOGIN_ERROR));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
